﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Collections;

namespace HostTool.Protocol
{
   public class FrameFilter:IFrameFilter
    {

        const int MAX_FRAME_NUM = 100;
        AutoResetEvent rxEvent = new AutoResetEvent(false);
        LinkedList<Frame> listFrame = new LinkedList<Frame>();



        public FrameFilter()
        {
            this.FilterDstPort = -1;
            this.FilterSrcPort = -1;
            this.FilterTransaction = -1;
            this.FilterCmd = -1;
        }

        public int FilterDstPort
        {
            get;
            set;
        }

        public int FilterSrcPort
        {
            get;
            set;
        }

        public int FilterTransaction
        {
            get;
            set;
        }

        public int FilterCmd
        {
            get;
            set;
        }


        public int FrameNum
        {
            get
            {
                return listFrame.Count; //是否加锁
            }
        }




        public void ClearFrame()
        {
            lock (((ICollection)(listFrame)).SyncRoot)
            {
                listFrame.Clear();
                rxEvent.Reset();
            }
        }

        public Frame GetFrame(int timeout)
        {
            Frame frame = null;
            lock (((ICollection)(listFrame)).SyncRoot)
            {
                if (listFrame.Count > 0)
                {
                    frame = listFrame.First.Value;
                    //listFrame.RemoveFirst();
                    listFrame.Remove(frame);
                }
            }
            if (frame != null || timeout == 0) return frame;

            if (timeout > 0)
            {
                rxEvent.WaitOne(timeout, false);
            }
            else
            {
                rxEvent.WaitOne();
            }

            return GetFrame(0);
        }



        #region IFrameFilter 成员

        public bool Match(Frame frame)
        {
            if (FilterSrcPort >= 0 && FilterSrcPort != frame.SrcPort) return false;
            if (FilterDstPort >= 0 && FilterDstPort != frame.DestPort) return false;
            if (FilterCmd >= 0 && FilterCmd != frame.Cmd) return false;
            if (FilterTransaction >= 0 && FilterTransaction != frame.Transaction) return false;

            return true;
        }

        public void AddFrame(Frame frame)
        {
            lock (((ICollection)listFrame).SyncRoot)
            {
                if (listFrame.Count > MAX_FRAME_NUM)
                {
                    listFrame.RemoveFirst();
                }
                listFrame.AddLast(frame);

                rxEvent.Set();
            }
        }

        #endregion
    }
}
